package cn.com.dcsgo.utils;

import cn.com.dcsgo.domain.po.SysDictData;
import cn.com.dcsgo.mapper.SysDictDataMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 字典数据本地缓存
 *
 * @author Dcsgo
 * @since 26/5/2025 上午 11:17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DictDataLocalCache {
    private final SysDictDataMapper sysDictDataMapper;

    /**
     * 字典类型:字典数据
     */
    private final Map<String, List<SysDictData>> cache = new ConcurrentHashMap<>();

    /**
     * 刷新缓存
     */
    public void refresh() {
        cache.clear();
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectAll();
        cache.putAll(
                sysDictDataList.stream().collect(Collectors.groupingBy(SysDictData::getDictType))
        );
        log.debug("after refresh() cache:");
        log.debug("{}", cache);
    }

    /**
     * 根据字典类型获取字典数据
     *
     * @param dictType 字典类型
     * @return 字典类型关联的字典数据，字典类型不存在返回 null
     */
    public List<SysDictData> get(String dictType) {
        return cache.get(dictType);
    }

    /**
     * 添加字典数据到缓存
     *
     * @param dictType        字典类型
     * @param sysDictDataList 字典数据集合
     */
    public void add(String dictType, List<SysDictData> sysDictDataList) {
        cache.put(dictType, sysDictDataList);
    }

    /**
     * 清空缓存
     */
    public void clear() {
        cache.clear();
    }
}
